﻿using System.Net.Sockets;
using System.Net;
using System.Text;
using System;
/*
 作者:zs
日期：2022.3.17
功能：KCP的.net库文件
*/
namespace PENet
{
  public   class KCPNet<T>where T:KCPSession,new ()
    {

        UdpClient udp;
        IPEndPoint remotePoint;
        public T clientSession;
        #region UDP

        public void StartAsClient(string ip,int port) 
        {
            udp = new UdpClient(0);
            remotePoint = new IPEndPoint(IPAddress.Parse(ip),port);
            KCPTool.ColorLog(KCPLogColor.Green,"Clinet start...");

            Task.Run(cline);
        }

        //获取全局的ID
        public void ConnectServer() 
        {
            SendUDPMsg(new byte[4], remotePoint);
        }

        public async void ClientRecive() 
        {
            UdpReceiveResult result;
            while (true)
            {
                try
                {
                    if(ct)

                    result = await udp.ReceiveAsync();
                    if (Equals(remotePoint, result.RemoteEndPoint))
                    {
                        uint sid = BitConverter.ToUInt32(result.Buffer, 0);
                        if (sid == 0)
                        {
                            //sid 数据
                            if (clientSession != null && clientSession.IsConnected())
                            {
                                //已经建立连接，初始划完成，收到了多次Sid
                                KCPTool.Warn("客户端是多余的");
                            }
                            else 
                            {
                                //未初始化，收到服务器分配的Sid
                                sid = BitConverter.ToUInt32(result.Buffer,4);
                                KCPTool.ColorLog(KCPLogColor.Green, "UDP请求Sid",sid);
                                clientSession = new T();
                                clientSession.InitSession(sid, SendUDPMsg, remotePoint);
                                clientSession.OnSessionClose = OnClientSessionClose(sid);
                            }
                        }
                        else 
                        {
                        //sid 建立连接  todo 业务逻辑处理
                        }
                    }
                    else 
                    {
                        KCPTool.Warn("客户端收到是非法目标的数据");
                    }
                }
                catch (System.Exception e)
                {

                    KCPTool.Warn("Client udp Recive:{0}",e.ToString());
                }
            }
        }
        void OnClientSessionClose(uint sid) 
        {
            //客户端死循环终止掉
            cts.Cancel();
            if (udp!=null) 
            {
                udp.Close();
                udp = null;
            }
            KCPTool.Warn("客户端Session关闭Sid是：{0}",sid);
        }
        public void CloseClinet() 
        {

            if (clientSession!= null) 
            {
                clientSession.CloseSession();
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="remotePoint">远端主机</param>
        void SendUDPMsg(byte[] bytes,IPEndPoint remotePoint) 
        {
            if (udp!=null) 
            {
                udp.SendAsync(bytes, bytes.Length,remotePoint);
            }
        }

    }
}
